<template>
  <div class="chart-container">
    <div class="year-selector">
      <!-- <span>选择年份：</span> -->
      <el-select v-model="selectedYear" placeholder="请选择年份" @change="updateChart">
        <el-option v-for="year in yearList" :key="year" :label="year" :value="year" />
      </el-select>
    </div>
    <div ref="chartRef" style="width: 100%; height: calc(100% - 40px)"></div>
  </div>
</template>

<script lang="ts" setup>
import * as echarts from 'echarts'
import type { EChartsOption } from 'echarts'
import { StatisticsApi } from '@/api/zszx/statistics/index'

const chartRef = ref<HTMLDivElement | null>(null)

const selectedYear = ref(new Date().getFullYear())
const yearList = ref<number[]>([])

for (let year = 2024; year <= new Date().getFullYear(); year++) {
  yearList.value.push(year)
}

const getStatistics = async (year: number) => {
  const res = await StatisticsApi.annualRentCountAmount(year)
  // console.log('annualRentCountAmount', res)

  return [
    {
      name: '已支付',
      count: res.rentPaidCount,
      amount: res.rentPaidAmount
    },
    {
      name: '未支付',
      count: res.rentUnPaytCount,
      amount: res.rentUnPayAmount
    }
  ]
}

const updateChart = async () => {
  if (!chartRef.value) return

  const myChart = echarts.getInstanceByDom(chartRef.value) || echarts.init(chartRef.value)
  const yearData = await getStatistics(selectedYear.value)
  console.log('yearData', selectedYear.value, yearData)

  const option: EChartsOption = {
    tooltip: {
      trigger: 'item',
      formatter: (params: any) => {
        const data = yearData[params.dataIndex]
        const isInner = params.seriesIndex === 0
        const valueType = isInner ? '数量' : '金额'
        const value = isInner ? data.count : data.amount
        const unit = isInner ? '个' : '元'

        return `
          <div style="font-weight:bold">${data.name} (${selectedYear.value}年)</div>
          <div>合同总数量: ${data.count}个</div>
          <div>合同总金额: ¥${data.amount.toLocaleString()}</div>
          <div>${valueType}: ${value}${unit} (${params.percent}%)</div>
        `
      }
    },
    legend: {
      orient: 'vertical',
      right: 10,
      bottom: '15',
      data: yearData.map((d) => d.name)
    },
    series: [
      // 内圈：合同数量
      {
        name: '合同数量',
        type: 'pie',
        radius: [0, '40%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: true,
          position: 'inside',
          formatter: '{b}\n{c}个',
          fontSize: 12,
          fontWeight: 'bold'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '18',
            fontWeight: 'bold',
            formatter: '{b}\n{c}个 ({d}%)'
          }
        },
        labelLine: {
          show: false
        },
        data: yearData.map((d) => ({
          value: d.count,
          name: d.name
        }))
      },
      // 外圈：合同金额（带引线和标注）
      {
        name: '合同金额',
        type: 'pie',
        radius: ['50%', '70%'],
        avoidLabelOverlap: true,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: true,
          position: 'outside',
          formatter: '{b}: ¥{c}',
          fontSize: 12,
          fontWeight: 'bold',
          align: 'center',
          backgroundColor: '#fff',
          padding: [3, 5],
          borderRadius: 4,
          borderWidth: 1,
          borderColor: '#ccc'
        },
        labelLine: {
          show: true,
          length: 20,
          length2: 15,
          smooth: true,
          lineStyle: {
            width: 1,
            type: 'solid'
          }
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 14,
            fontWeight: 'bold'
          }
        },
        data: yearData.map((d) => ({
          value: d.amount,
          name: d.name
        }))
      }
    ]
  }

  myChart.setOption(option)
}

onMounted(() => {
  updateChart()
  // 窗口大小变化时重绘图表
  window.addEventListener('resize', () => {
    if (chartRef.value) {
      const myChart = echarts.getInstanceByDom(chartRef.value)
      myChart?.resize()
    }
  })
})
</script>

<style scoped>
.chart-container {
  display: flex;
  width: 100%;
  height: 100%;
  flex-direction: column;
}

.year-selector {
  display: flex;
  padding: 0;
  align-items: center;
}

.year-selector span {
  margin-right: 10px;
  font-size: 14px;
}
</style>
